package com.example.myproject.service.serviceImpl;


import com.example.myproject.model.ContractAssignment;
import com.example.myproject.model.CustomUserDetails;
import com.example.myproject.model.User;
import com.example.myproject.model.UserRoleRelation;
import com.example.myproject.repository.ContractAssignmentRepository;
import com.example.myproject.repository.UserRepository;
import com.example.myproject.repository.UserRoleRelationRepository;
import com.example.myproject.service.CustomUserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class CustomUserDetailsServiceImpl implements CustomUserDetailsService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserRoleRelationRepository userRoleRelationRepository;
    @Autowired
    private ContractAssignmentRepository contractAssignmentRepository;

    private static final Logger log = LoggerFactory.getLogger(CustomUserDetailsServiceImpl.class);

    public CustomUserDetailsServiceImpl(UserRepository userRepository, UserRoleRelationRepository userRoleRelationRepository) {
        this.userRepository = userRepository;
        this.userRoleRelationRepository = userRoleRelationRepository;
    }

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("开始加载用户: {}", username);
        User user = userRepository.findByUsername(username);
        if (user == null) {
            log.warn("未找到用户: {}", username);
            throw new UsernameNotFoundException("未找到用户名为 " + username + " 的用户");
        }
        log.debug("用户加载成功: {}", user);

        Set<GrantedAuthority> authorities = getUserAuthorities(user.getId());
        log.info("已加载用户: {} 与权限: {}", username, authorities);

        Map<Long, List<String>> contractRoles = new HashMap<>(); // 初始化为空map
        try {
            contractRoles = contractAssignmentRepository.findAllByUserId(user.getId())
                    .stream()
                    .collect(Collectors.groupingBy(
                            ContractAssignment::getContractId,
                            Collectors.mapping(ContractAssignment::getRole, Collectors.toList())
                    ));
            log.debug("查询用户关联的合同及角色成功: {}", contractRoles);
        } catch (Exception e) {
            log.error("查询用户关联的合同及角色失败: {}", e.getMessage(), e);
        }

        log.info("最终用户详细信息: {}", new CustomUserDetails(user.getUsername(), user.getPassword(), authorities, contractRoles));
        return new CustomUserDetails(user.getUsername(), user.getPassword(), authorities, contractRoles);
    }

    private Set<GrantedAuthority> getUserAuthorities(Long userId) {
        log.debug("开始查询用户权限: {}", userId);

        Set<GrantedAuthority> authorities = new HashSet<>();
        Set<UserRoleRelation> relations = userRoleRelationRepository.findAllByUserId(userId);

        for (UserRoleRelation relation : relations) {
            log.debug("用户ID {} 的角色 {} 包含的功能字符串: {}", userId, relation.getRole().getName(), relation.getRole().getFunctions());
            String functions = relation.getRole().getFunctions();
            if (functions != null && !functions.trim().isEmpty()) {
                String[] permissionArray = functions.split(",");
                for (String permission : permissionArray) {
                    if (permission != null && !permission.trim().isEmpty()) {
                        authorities.add(new SimpleGrantedAuthority(permission.trim()));
                        log.debug("为用户ID {} 添加权限: {}", userId, permission.trim());
                    } else {
                        log.warn("发现无效权限，用户ID {} 的权限: {}", userId, permission);
                    }
                }
            } else {
                log.warn("用户ID {} 的角色 {} 没有有效的功能字符串", userId, relation.getRole().getName());
            }
        }

        log.info("用户ID {} 的所有权限加载完成: {}", userId, authorities);
        return authorities;
    }
}
